import { Popup, NavBar, InfiniteScroll, Toast } from 'antd-mobile'

import CommentItem from '../CommentItem'
import CommentFooter from '../CommentFooter'
import CommentInput from '../CommentInput'

import styles from './index.module.scss'
import { ArticleCommentItem } from '@/types/data'
import { useRef, useState } from 'react'
import { addComment, getComments } from '@/api/article'
import { useParams } from 'react-router-dom'

type Props = {
  // onClose: () => void
  onClose: (commentId: string, total: number) => void
  commentItem: ArticleCommentItem
}

const Reply = ({ onClose, commentItem }: Props) => {
  // 1. 获取回复列表
  // 拿到原始评论的 id
  const { com_id } = commentItem
  const params = useParams<{ artId: string }>()
  // 评论项的回复列表状态
  const [replyList, setReplyList] = useState<ArticleCommentItem[]>([])
  // 控制是否加载完成
  const [hasMore, setHasMore] = useState(true)
  // 分页偏移量offset
  const offset = useRef<string | null>(null)
  const loadMoreComments = async () => {
    const { data } = await getComments('c', com_id, offset.current)
    setReplyList([...replyList, ...data.results])
    if (replyList.length === data.total_count) {
      setHasMore(false)
    } else {
      offset.current = data.last_id
    }
  }

  // 2. 添加回复
  const [replyInput, setReplyInput] = useState(false)

  const onReplyInputShow = () => setReplyInput(true)
  const onReplyInputHide = () => setReplyInput(false)

  const onAddReply = async (content: string) => {
    const { data } = await addComment({
      target: com_id,
      content,
      art_id: params.artId,
    })
    // 向回复列表追加最新回复数据
    setReplyList([data.new_obj, ...replyList])
    // 关闭评论抽屉
    onReplyInputHide()
    Toast.show('回复成功')
  }

  return (
    <div className={styles.root}>
      <div className="reply-wrapper">
        <NavBar
          className="transparent-navbar"
          onBack={() => onClose(com_id, replyList.length)}>
          {replyList.length}条回复
        </NavBar>

        {/* 要回复的评论 */}
        <div className="origin-comment">
          <CommentItem type="origin" {...commentItem} />
        </div>

        <div className="reply-list">
          <div className="reply-header">全部回复</div>
          {replyList.map((item) => (
            <CommentItem key={item.com_id} {...item} type="reply" />
          ))}
          <InfiniteScroll hasMore={hasMore} loadMore={loadMoreComments} />
        </div>

        <CommentFooter
          placeholder="去回复"
          onCommentPopup={onReplyInputShow}
          type="reply"
        />
      </div>

      {/* 回复文本框对应的抽屉 */}
      <Popup
        destroyOnClose
        className="reply-popup"
        position="bottom"
        visible={replyInput}>
        <CommentInput
          name="reply"
          onClose={onReplyInputHide}
          onAddComment={onAddReply}
        />
      </Popup>
    </div>
  )
}

export default Reply
